/* This javascript file has a .php extention because it needs access 
   to the php session variables; treat it as a just another javascript file.
   */

$(document).ready(function() {
	
	/*
	* Expand and collapse the login panel when the "open panel" 
	* text is clicked. The callback function in slideToggle changes
	* the text from "open" to "close"
	*/
	$("#open").click(function(){
		openPanel();
	});	
	
	/*
	* Causes the "Create New Project" button in the panel
	* to slide up and down when clicked. (The contactForm is
	* what is actually moving)
	*/
	$("#newProjectButton").click(function(){
		$("#contactForm").slideToggle(500,"easeInOutExpo");
	});



	/*
	* Make sure the user enters at least one character.
	* Attach the addProject() function to the add_project_button's click
	*/
	$("#add_project_button").click(function(){
		if($('#name').val().length >= 1){
			addProject();
		}
		
		else{
			alert("Please, enter at least a character");
		}
	});
		
		
	/*
	* Logs the user out by attaching a post targeted at functions/logout.php
	* to the logout button. No post parameters are required.
	*/
	$("#logout").click(function(){
		$.post("functions/logout.php", {"username":user}, function(){
			window.location = "index.php";
		});
	});
	
	/*
	* Logs the user in by attaching a post targeted at functions/login.php
	* to the login button #bt_login. The username and password parameters 
	* are taken from the input fields on the webpage.
	*/
	$("#bt_login").click(function(){
		var user = $("#username").val();
		var pass = $("#password").val();
		
		$.post("functions/login.php", {"username":user, "password":pass}, function(data){
			if(data == "username or password incorrect")
				alert(data);
			else{
				window.location = "index.php";}
		});
	});
	
	/*
	* Terminate user's account by deleting all data associated with him/her
	*/
	function terminate(user, project){
		var user = user;
		var project = project;
		if(project != ""){
			$.post("functions/delete_user.php", {"user":user, "prname":project});
		}
		else{
			$.post("functions/terminate_user.php", {"user":user});
		}
	};
	
	$("#closeAccnt").click(
		function(){
			if(confirm("Are you sure you want to terminate your account?")){
				$.post("functions/closeAccnt.php", {"username":user}, function(data){
					//Convert data into an array
					var dSplit = data.split(",");
					if(dSplit.length != 0){
						$.each(dSplit, function(index, value) {  
						  terminate(user, value);
						});
					}
					else{
						terminate(user, "");
					}
					window.location = "index.php";
				});
			}
		}
	);
	
	
	
	/*
	* Small key listener to allow users to press enter instead of clicking
	* the login button
	*/
	$("#username, #password").keyup(function(e){
		if(e.keyCode == 13){
			$("#bt_login").click();
		}
	});
	
	/*
	* Registers a new user by sending a post to function/register.php.
	* Function is attached to the click event for the #bt_register button.
	* Documentation on the details of registering are in function/register.php
	*/
	$("#bt_register").click(function(){
		var user = $("#register_username").val();
		var pass = $("#register_password").val();
				
		$.post("functions/register.php", {"username":user, "password":pass} , function(data){
			if(data == "User successfully created"){
				$("#register_username").val("");
				$("#register_password").val("");
			}
			alert(data);
		});
	});
	
	/*
	* Small key listener to allow users to press enter instead of clicking
	* the register button
	*/
	$("#register_username, #register_password").keyup(function(e){
		if(e.keyCode == 13){
			$("#bt_register").click();
		}
	});
	
	/*
	* Slides the panel up and down. Function is defined after
	* the document.ready function. 
	*/
	setTimeout('openPanel()', 200);
		
});

/*
* Loads the the project that is currently selected in the panel into the 
* pageContent div.
* If no project is selected, a message telling the user to select a project is displayed.
*/
function showProject(){
	if($("#project_list option:selected").text() == "Select A Project:"){
		alert("Please select a project.");
	}
	else{
		$.post("project/index.php", {"prname":$("#project_list option:selected").text(), "username":$("#username_lable").text()}, function(data){
			openPanel();
			var info = data;
			$("#pageContent").fadeOut(500, function(){
				$("#pageContent").html(info);
				$("#pageContent").fadeIn(500);
			});
			
			});
	}
};

/*
* Disassociates a user from the selected project.
* If the user is the creator, table [pname] is dropped, and the project is deleted from the projects table.
* The deleted project is removed from the project lists of all the participating users.
* If the user is not the creator, user's association with the selected project is deleted from the projects table.
* The deleted project is removed from the user's projects list.
* After deletion a message is displayed.
*/
function deleteProject(){
	var project_name = $("#project_list option:selected").text();
	if(confirm("Are you sure you want to delete \'" + project_name + "\'?")){
		$.post("functions/delete_project.php", {"prname":project_name, "user":user}, function(){
			getProjects();
		});
	}
	
};


/*
* Similar to showProject(), but it does not cause a fade effect and it
* does not move the panel. This is the start of a 'synchronous' application
* between multiple clients...
*/
function refreshProject(){
	$.post("project/index.php", {"prname":$("#project_list option:selected").text()}, function(data){
			$("#pageContent").html(data);	
		});
};

function refreshBoard(){
	$.post("functions/get_notes.php", {"prname":$("#project_list option:selected").text()}, function(data){
			$("#board").html(data);	
		});
};


/*
 * This function gets the users and displays them.
 * Also, whenever a user logs in/out a sliding message box alerts the rest of the users that have the logged in/out users as a team member.
 * In other words, the sliding message box will not appear in a project where the user is not a participant.
 * */
function refreshUsers(){
	
	//Options for the sliding message
	var mssg = {id: 'message_from_top',
	    position: 'bottom',
	    size: 50,
	    backgroundColor: 'rgba(255, 64, 64, 0.8)',
	    delay: 3500,
	    speed: 500,
	    fontSize: '20px'
	   };
	
	$.post("functions/get_participants.php", {"pname":$("#project_name").text()}, function(data){
	        
			//Get all usernames that are online
			var divArr = []; 
	        $('#users').find('p.usersOnline').each(function() {
				divArr.push($(this).text());
			});
	        
	        //Copy all usernames that are online
	        var copyOf = divArr;
	        
	        var userStatus;
	        
	        //Refresh div
	        $("#users").html(data);
	        
	        //Get a new list of all usernames that are online
	        var divArr = []; 
	        $('#users').find('p.usersOnline').each(function() {
				divArr.push($(this).text());
			});
	
	
	        /*Compare the list obtained before '#users' refresh with the list after the refresh. 
	         *If no one has logged in or logged out, the two lists are the same. 
	         *@serStatus is FALSE
	         */
	        if($(divArr).not(copyOf).get().length == 0 && $(copyOf).not(divArr).get().length == 0){
	                userStatus = 0;
	        }
	
	        /*When somebody logs in/out @userStatus is toggled to TRUE
	         *Two lists are made by comparing the lists from before and after refreshing '#users':
	         *		One list has the users that logged in
	         *		The other one has the users that logged out
	         */
	        else{
	                userStatus = 1;
	                
	                //@gotIn Contains elements that are in divArr but not in copyOf
	                var gotIn = new Array();
	                gotIn = jQuery.grep(divArr,function (item) {
	                        return jQuery.inArray(item, copyOf) < 0;
	                });
	                
	                //@gotOut Contains elements that are in copyOff but not in divArr
	                var gotOut = new Array();
	                gotOut = jQuery.grep(copyOf,function(item){
	                        return jQuery.inArray(item, divArr) < 0;
	                });
	        }
	
	        //If there is difference between divArr and copyOff, display the appropriate message
	        if(userStatus){
	
	                //If somebody logged in and no one logged out
	                if(gotIn.length != 0 && gotOut.length == 0){
	                      $.showMessage(gotIn + ' ' + ' logged in', mssg);
	                }
	
	                //If somebody logged out and no one logged in
	                else if(gotOut.length != 0 && gotIn.length == 0){
	                      $.showMessage(gotOut + ' ' + ' logged out', mssg);
	                }
	
	                //If somebody logged in and somebody else logged out
	                else if(gotIn.length != 0 && gotOut.length !=0){
	                      $.showMessage(gotIn + ' ' + ' logged in ' + '....... ' + gotOut + ' ' + ' logged out', mssg);
	                }
	        }
	
	        var divArr = []; 
	        $('#users').find('p.usersOnline').each(function() {
				divArr.push($(this).text());
			});
	});
};


function refreshChat(){
	$.post("functions/get_chat.php", {"project":$("#project_name").text()}, function(data){
		$("#chatText").html(data);
	});
}

/******************************** Start refreshing div children counters ******************************************/
function refreshDiv0Children(){
	var div = "note_start";

	$.post("functions/get_div0Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".start_kids").html(data);
	});
}

function refreshDiv1Children(){
	var div = "one_point_main";

	$.post("functions/get_div1Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".one_kids").html(data);
	});
}

function refreshDiv2Children(){
	var div = "two_points_main";

	$.post("functions/get_div2Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".two_kids").html(data);
	});
}

function refreshDiv3Children(){
	var div = "three_points_main";

	$.post("functions/get_div3Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".three_kids").html(data);
	});
}
	
function refreshDiv4Children(){
	var div = "five_points_main";

	$.post("functions/get_div4Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".five_kids").html(data);
	});
}

function refreshDiv5Children(){
	var div = "eight_points_main";

	$.post("functions/get_div5Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".eight_kids").html(data);
	});
}
	
function refreshDiv6Children(){
	var div = "thirteen_points_main";

	$.post("functions/get_div6Info.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".thirteen_kids").html(data);
	});
}
/******************************** End refreshing div children counters ******************************************/


/******************************** Start refreshing div points ******************************************/
function refreshDiv1Points(){
	var div = "one_point_main";

	$.post("functions/get_div1Points.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".one_size").html(data);
	});
}

function refreshDiv2Points(){
	var div = "two_points_main";

	$.post("functions/get_div2Points.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".two_size").html(data);
	});
}

function refreshDiv3Points(){
	var div = "three_points_main";

	$.post("functions/get_div3Points.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".three_size").html(data);
	});
}
	
function refreshDiv4Points(){
	var div = "five_points_main";

	$.post("functions/get_div4Points.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".five_size").html(data);
	});
}

function refreshDiv5Points(){
	var div = "eight_points_main";

	$.post("functions/get_div5Points.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".eight_size").html(data);
	});
}
	
function refreshDiv6Points(){
	var div = "thirteen_points_main";

	$.post("functions/get_div6Points.php", {"project":$("#project_name").text(), "div":div}, function(data){
		$(".thirteen_size").html(data);
	});
}
/******************************** End refreshing div points ******************************************/

/*
* Much like the showProject() function, but opens in project in a new tab and is
* bound to text on the project page instead of the panel. Could possibly be merged
* together with showProject() in the future...
*/
function showProjectTab(){
	$.post("project/index.php", {"prname":$("#project_list option:selected").text()}, function(data){
		openPanel();
		var info = data;
		$("#pageContent").fadeOut(500, function(){
			window.open(info);
			$("#pageContent").fadeIn(500);
		});
		
		});
};

/*
* Toggles the panel open and closed
*/
function openPanel(){
		$("div#panel").slideToggle(500,"easeInOutExpo", function(){
			if ($(this).is(':hidden')) {
					$("#open").text("Open Panel");
				} else {
					$("#open").text("Close Panel");
				}
		});
}

